package xin.yangshuai.websocket01.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;


/**
 * WebSocketServer
 *
 * @author shuai
 * @date 2022/9/5
 */
@Component
@ServerEndpoint("/websocket")
public class WebSocketServer {

    public WebSocketServer() {
        System.out.println("123456789=======================");
    }

    private Logger logger = LoggerFactory.getLogger(WebSocketServer.class);

    @OnOpen
    public void onOpen(Session session) {
        logger.info("客户端：{}连接成功", session.getId());
    }

    @OnClose
    public void onClose(Session session) {
        logger.info("客户端：{}连接断开", session.getId());

    }

    @OnMessage
    public String onMsg(String message, Session session) {
        logger.info("从客户端：{} 收到<--:{}", session.getId(), message);

        String send = message.toUpperCase();
        String result = "客户：%s您好，来自server 的消息:%s";
        result = String.format(result, session.getId(), send);
        return "来自server 的消息：" + result;
    }

    @OnError
    public void onError(Throwable throwable, Session session) {
        logger.info("客户端：{}异常", session.getId());

    }
}
